package com.example.java_gobang2.api;

import com.example.java_gobang2.game.OnlineUserManager;
import com.example.java_gobang2.game.RoomManager;
import com.example.java_gobang2.mapper.UserMapper;
import com.example.java_gobang2.model.Room;
import com.example.java_gobang2.model.RoomReadyResponse;
import com.example.java_gobang2.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class AIGameAPI extends TextWebSocketHandler {
    @Autowired
    private RoomManager roomManager;
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private UserMapper userMapper;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        onlineUserManager.removeGameHall(user.getUserId());
        log.info("退出游戏大厅");
        onlineUserManager.setGameRoom(user.getUserId(), session);
        log.info("与AI建立连接,userid:{}",user.getUserId());
        RoomReadyResponse response = new RoomReadyResponse();
        if (user == null) {
            response.setOk(false);
            response.setError("玩家不存在");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
        Room room = roomManager.getRoom(user.getUserId());
        synchronized (room) {
            room.setUser1(user);
            room.setUser2(userMapper.selectByUsername("ai"));
            gameStart(room,room.getUser1().getUserId(),room.getUser2().getUserId());
            return;
//            if (room.getUser1() == null) {
//                room.setUser1(user);
//                return;
//            }
//            if (room.getUser2() == null) {
//                room.setUser2(user);
//                gameStart(room,room.getUser1().getUserId(),room.getUser2().getUserId());
//                return;
//            }
//            response.setOk(false);
//            response.setError("异常错误,请重试");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    private void gameStart(Room room, int userId1, int userId2) throws IOException {
        RoomReadyResponse response = new RoomReadyResponse();
        response.setThisUserId(userId1);
        response.setThatUserId(userId2);
        response.setWhiteUserId(room.getUser1().getUserId());
        response.setRoomId(room.getRoomId());
        response.setMessage("游戏开始");
        onlineUserManager.getGameRoom(userId1).sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        roomManager.putChessAI(message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
